<template>
  <el-card style="width: 500px;">
    <el-form label-width="80px" size="small">

      <el-upload
              class="avatar-uploader"
              action="http://localhost:9091/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
      >
        <img v-if="form.avatarUrl" :src="form.avatarUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>

      <el-form-item label="用户名">
        <el-input v-model="form.username" autocomplete="off" disabled></el-input>
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="form.nickname" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="form.email" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="电话">
        <el-input type="number" v-model.number="form.phone" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="地址">
        <el-input v-model="form.address" autocomplete="off" type="textarea"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">确 定</el-button>
      </el-form-item>
    </el-form>
    <hr>
    <h1>mavonEditor</h1>
    <div>
      <mavon-editor v-model="value" :ishljs = "true" ref="md"  @imgAdd="$imgAdd" @imgDel="$imgDel"/>
    </div>

    <div>
      <div class="markdown-body" v-html="this.md"></div>
    </div>

  </el-card>
</template>

<script>
  import 'github-markdown-css'
export default {
  name: "Person",
  data() {
    return {
      form: {},
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
    //  markdown
      value: '',
      value1: '',
      img_file: []
    }
  },
  created() {
    // this.request.get("/user/username/" + this.user.username).then(res => {
    //   if (res.code === '200') {
    //     this.form = res.data
    //   }
    // })

    this.getUser().then(res => {
      console.log(res)
      this.form = res
    })
  },
  computed:{
    md(){
      var MardownIt = require("markdown-it")
      var md = new MardownIt()
      return md.render(this.value)
    }
  },
  methods: {
    save() {
      this.request.post("/user", this.form).then(res => {

          if (res.code === '200') {
            this.$message.success("保存成功")

            // 更新浏览器存储的用户信息
            this.getUser().then(res => {
              res.token = JSON.parse(localStorage.getItem("user")).token
              localStorage.setItem("user", JSON.stringify(res))
              //person=>Manage(子传父)=>Header(父传子)
              this.$emit("refreshUser")
            })


        } else {
          this.$message.error("保存失败")
        }
      })
    },
    //异步改为同步
    async getUser() {
      return (await this.request.get("/user/username/" + this.user.username)).data
    },
    //头像上传成功的回调
    handleAvatarSuccess(res) {
      this.form.avatarUrl = res
    },


      // 上传图片
      $imgAdd(pos, $file){
        console.log(this.$refs.md);

        // 第一步.将图片上传到服务器.
        var formdata = new FormData();
        formdata.append('file', $file);
        this.img_file[pos] = $file;

        this.request({
          url: 'http://localhost:9091/file/upload',
          method: 'post',
          data: formdata,
          headers: { 'Content-Type': 'multipart/form-data' },
        }).then((data) => {
          console.log(data)
          // 第二步.将返回的url替换到文本原位置![...](./0) -> ![...](url)
          /**
           * $vm 指为mavonEditor实例，可以通过如下两种方式获取
           * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
           * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
           */
          console.log(data.data)
          this.$refs.md.$img2Url(pos,data.data);

        })
      },

    //删除图片
    $imgDel(pos) {
      delete this.img_file[pos];
    }
    }

}
</script>


<style>
  .avatar-uploader {
    text-align: center;
    padding-bottom: 10px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 138px;
    height: 138px;
    line-height: 138px;
    text-align: center;
  }
  .avatar {
    width: 138px;
    height: 138px;
    display: block;
  }
</style>
